package com.lc.cehui.ui.activity;

import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.cehui.R;
import com.lc.cehui.app.AppActivity;
import com.lc.cehui.dialog.AddressDialog;
import com.lc.cehui.http.glide.GlideApp;
import com.lc.cehui.http.request.CompanyListApi;
import com.lc.cehui.http.response.CompanyListBean;
import com.lc.cehui.http.response.CompanyTypeBean;
import com.lc.cehui.other.KeyboardWatcher;
import com.lc.cehui.ui.activity.home.ParticularsActivity;
import com.lc.cehui.ui.adapter.ChoiceAdapter;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 企业列表
 */
public class EnterpriseListActivity extends AppActivity implements KeyboardWatcher.SoftKeyboardStateListener,
        TextView.OnEditorActionListener{

    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.ll_seach)
    LinearLayout llSeach;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    TwinklingRefreshLayout refreshLayout;
    @BindView(R.id.tv_qy)
    TextView tvQy;
    @BindView(R.id.tv_hy)
    TextView tvHy;
    @BindView(R.id.tv_xz)
    TextView tvXz;
    @BindView(R.id.tv_gm)
    TextView tvGm;
    @BindView(R.id.recyclerView_choice)
    RecyclerView recyclerViewChoice;
    @BindView(R.id.ll_choice)
    LinearLayout llChoice;
    @BindView(R.id.et_text)
    EditText etText;

    private BaseQuickAdapter adapter;
    private ChoiceAdapter choiceAdapter;
    private String choiceType = "";
    private String Type="";
    private String nature="";
    private String industry="";
    private String scale="";
    private String key="";
    private int mPage = 1;
    private  List<CompanyTypeBean.DataBean> typelist = new ArrayList<>();
    private List<CompanyTypeBean.DataBean.List2Bean> list=new ArrayList<>();
    /**
     * 省
     */
    private String mProvince = "";
    /**
     * 市
     */
    private String mCity = "";
    /**
     * 区
     */
    private String mArea = "";
    private List<CompanyListBean.DataBean> datalist=new ArrayList<>();
    private String flag;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_enterprise_list;
    }

    @Override
    protected void initView() {
        datalist.clear();
        company_list(mPage,key,mProvince,mCity,mArea,nature,industry,scale);

        company_type();
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                Log.e("TAG", "onRefresh:---- " );
                super.onRefresh(refreshLayout);
//                new Handler().postDelayed(() -> {

                mPage = 1;
                datalist.clear();
                company_list(mPage,key,mProvince,mCity,mArea,nature,industry,scale);
                refreshLayout.finishRefreshing();
//                }, 1000);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);



                if (flag.equals("T")) {
                    mPage++;
                    company_list(mPage,key,mProvince,mCity,mArea,nature,industry,scale);
                } else {

                }
                refreshLayout.finishLoadmore();

            }
        });

        etText.setOnEditorActionListener(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter = new BaseQuickAdapter<CompanyListBean.DataBean, BaseViewHolder>(R.layout.adapter_enterlist,datalist) {
            @Override
            protected void convert(@NonNull BaseViewHolder baseViewHolder, CompanyListBean.DataBean bean) {
                GlideApp.with(EnterpriseListActivity.this).load(bean.getPicurl()).apply(new RequestOptions().placeholder(R.drawable.image11).error(R.drawable.image11)).into((ImageView) baseViewHolder.getView(R.id.im_logo));
                baseViewHolder.setText(R.id.tv_title, bean.getName());
                baseViewHolder.setText(R.id.tv_body, bean.getIndustry()+"  ｜ "+bean.getNature());
                baseViewHolder.setText(R.id.tv_work, bean.getWork());
                baseViewHolder.setText(R.id.tv_count, "等"+bean.getCount()+"个职位");

            }
        });
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//                企业详情
                startActivity(new Intent(EnterpriseListActivity.this, ParticularsActivity.class).putExtra("id",datalist.get(position).getCompany_id()+""));
            }
        });
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext());
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        recyclerViewChoice.setLayoutManager(layoutManager);

        choiceAdapter = new ChoiceAdapter(R.layout.adapter_choice_item, null);
        recyclerViewChoice.setAdapter(choiceAdapter);
        choiceAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                choiceType = choiceAdapter.getData().get(position).getId();
                 if (Type.equals("行业")){
                     industry =choiceAdapter.getData().get(position).getId();
                 }else if (Type.equals("性质")){
                     nature=choiceAdapter.getData().get(position).getId();
                 }else if (Type.equals("规模")){
                     scale=choiceAdapter.getData().get(position).getId();
                 }
                 mPage=1;
                datalist.clear();
                company_list(mPage,key,mProvince,mCity,mArea,nature,industry,scale);
                llChoice.setVisibility(View.GONE);
            }
        });
        showEmptyView(adapter);
    }

    private void company_type() {

        EasyHttp.post(this)
                .api("api/company_type")
                .request(new HttpCallback<CompanyTypeBean>(this) {

                    @Override
                    public void onSucceed(CompanyTypeBean data) {
                        typelist.addAll(data.getData());


                    }
                });
    }


    @Override
    protected void initData() {

    }

    @OnClick({R.id.tv_qy, R.id.tv_hy, R.id.tv_xz, R.id.tv_gm, R.id.ll_seach})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_seach:
                break;
            case R.id.tv_qy:
                setUI(tvQy, 0);

                break;
            case R.id.tv_hy:
                Type="行业";
                setUI(tvHy, 1);
                break;
            case R.id.tv_xz:
                Type="性质";
                setUI(tvXz, 2);
                break;
            case R.id.tv_gm:
                Type="规模";
                setUI(tvGm, 3);
                break;
        }
    }

    private void company_list(int mPage,String key,String province,String city,String district,String nature,String industry,String scale) {
        EasyHttp.post(this)
                .api(new CompanyListApi().setPage(mPage).setKey(key).setProvince(province).setCity(city).setDistrict(district).setNature(nature).setIndustry(industry).setScale(scale))
                .request(new HttpCallback<CompanyListBean>(this) {

                    @Override
                    public void onSucceed(CompanyListBean data) {

                        if (data.getCode().equals("200")) {
                            flag = data.getFlag();

                            datalist.addAll(data.getData());
                            adapter.setNewData(datalist);
                            adapter.notifyDataSetChanged();

                        }

                    }

                });
    }

    private void setUI(TextView textView, int type) {
        switch (type) {
            case 0:
                new AddressDialog.Builder(this)
                        .setTitle("选择地区")
                        // 设置默认省份
//                        .setProvince(mProvince)
                        // 设置默认城市（必须要先设置默认省份）
//                        .setCity(mCity)
                        // 不选择县级区域
                        //.setIgnoreArea()
                        .setListener((dialog, province, city, area) -> {

                            if (!tvQy.getText().toString().equals(city)) {
                                mProvince = province;
                                mCity = city;
                                mArea = area;
                                tvQy.setText(mCity);
                                llChoice.setVisibility(View.GONE);
                                mPage=1;
                                datalist.clear();
                                company_list(mPage,key,mProvince,mCity,mArea,nature,industry,scale);
                            }
                        })
                        .show();

                break;
            case 1:
                choiceAdapter.setNewInstance(lists("行业"));
                choiceAdapter.notifyDataSetChanged();
                llChoice.setVisibility(View.VISIBLE);
                break;
            case 2:
                choiceAdapter.setNewInstance(lists("性质"));
                choiceAdapter.notifyDataSetChanged();
                llChoice.setVisibility(View.VISIBLE);
                break;
            case 3:
                choiceAdapter.setNewInstance(lists("规模"));
                choiceAdapter.notifyDataSetChanged();
                llChoice.setVisibility(View.VISIBLE);
                break;
        }

        tvQy.setTextColor(getResources().getColor(R.color.color333333));
        tvHy.setTextColor(getResources().getColor(R.color.color333333));
        tvXz.setTextColor(getResources().getColor(R.color.color333333));
        tvGm.setTextColor(getResources().getColor(R.color.color333333));

        textView.setTextColor(getResources().getColor(R.color.blue168));
    }


    private List<CompanyTypeBean.DataBean.List2Bean> lists(String s) {

        list.clear();
        boolean isChecked = false;
        for (int i = 0; i < typelist.size(); i++) {
            if (typelist.get(i).getTitle().equals(s)) {
                list.addAll(typelist.get(i).getList2());
            }
        }
        for (int i = 0; i <list.size() ; i++) {

            if (choiceType.equals(list.get(i).getId())){
                isChecked = true;
                list.get(i).setSelect(true);
            } else {
                list.get(i).setSelect(false);
            }

        }




        CompanyTypeBean.DataBean.List2Bean bean = new CompanyTypeBean.DataBean.List2Bean();
        bean.setTitle("不限");
        if (!isChecked){
            bean.setSelect(true);
        }
        list.add(bean);

        return list;
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // 模拟点击登录按钮
            key=etText.getText().toString().trim();
            mPage=1;
            datalist.clear();
            company_list(mPage,key,mProvince,mCity,mArea,nature,industry,scale);
            hideKeyboard(getCurrentFocus());
//            搜索


        }
        return false;
    }

    @Override
    public void onSoftKeyboardOpened(int keyboardHeight) {

    }

    @Override
    public void onSoftKeyboardClosed() {

    }
}